<template>
  <div class="points-mall">
    <!-- 顶部积分信息 -->
    <header class="bg-gradient-to-r from-blue-600 to-purple-600 text-white">
      <div class="container mx-auto px-4 py-6">
        <div class="flex justify-between items-center">
          <div>
            <h1 class="text-2xl font-bold mb-2">积分商城</h1>
            <p class="text-blue-100">用积分兑换精美礼品</p>
          </div>
          <div class="text-right">
            <div class="text-3xl font-bold">{{ userPoints }}</div>
            <div class="text-sm text-blue-100">当前积分</div>
          </div>
        </div>
        
        <!-- 积分历史快速查看 -->
        <div class="mt-4 flex justify-between items-center">
          <div class="text-sm">
            <span class="text-blue-100">本月获得: </span>
            <span class="font-semibold">+{{ monthlyEarned }}</span>
          </div>
          <router-link to="/client/points-history" class="text-blue-100 hover:text-white text-sm">
            查看积分明细 <i class="fas fa-chevron-right"></i>
          </router-link>
        </div>
      </div>
    </header>

    <div class="container mx-auto px-4 py-6">
      <!-- 分类标签 -->
      <div class="category-tabs">
        <button 
          v-for="category in categories" 
          :key="category.key"
          @click="selectedCategory = category.key"
          :class="[
            'category-tab',
            selectedCategory === category.key ? 'active' : ''
          ]"
        >
          <i :class="category.icon" class="mr-1"></i>
          {{ category.name }}
        </button>
      </div>

      <!-- 热门推荐 -->
      <div v-if="selectedCategory === 'all'" class="mb-8">
        <h2 class="text-xl font-bold text-gray-800 mb-4">
          <i class="fas fa-fire text-red-500 mr-2"></i>热门推荐
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div 
            v-for="item in hotItems" 
            :key="item.id"
            class="product-card hover-scale"
          >
            <div class="relative">
              <img :src="item.image" :alt="item.name" class="product-image">
              <div class="badge badge-hot">
                热门
              </div>
              <div v-if="item.discount" class="badge badge-discount">
                {{ item.discount }}折
              </div>
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ item.name }}</h3>
              <p class="product-description">{{ item.description }}</p>
              <div class="product-price">
                <div class="flex items-center">
                  <span class="points-text">{{ item.points }}</span>
                  <span class="points-unit">积分</span>
                  <span v-if="item.originalPoints" class="original-points">
                    {{ item.originalPoints }}
                  </span>
                </div>
              </div>
              <button 
                @click="exchangeItem(item)"
                :disabled="userPoints < item.points"
                :class="[
                  'exchange-btn',
                  userPoints >= item.points ? 'available' : 'unavailable'
                ]"
              >
                {{ userPoints >= item.points ? '立即兑换' : '积分不足' }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="mb-8">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-bold text-gray-800">
            {{ getCategoryName(selectedCategory) }}
          </h2>
          <div class="flex items-center space-x-2">
            <select v-model="sortBy" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
              <option value="default">默认排序</option>
              <option value="points-asc">积分从低到高</option>
              <option value="points-desc">积分从高到低</option>
              <option value="popularity">热门优先</option>
            </select>
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          <div 
            v-for="item in filteredAndSortedItems" 
            :key="item.id"
            class="product-card hover-scale"
          >
            <div class="relative">
              <img :src="item.image" :alt="item.name" class="product-image">
              <div v-if="item.stock <= 10" class="badge badge-low-stock">
                仅剩{{ item.stock }}件
              </div>
              <div v-if="item.isNew" class="badge badge-new">
                新品
              </div>
            </div>
            <div class="product-info">
              <h3 class="product-title">{{ item.name }}</h3>
              <p class="product-description">{{ item.description }}</p>
              <div class="flex justify-between items-center mb-3">
                <div class="flex items-center">
                  <span class="points-text">{{ item.points }}</span>
                  <span class="points-unit">积分</span>
                </div>
                <div class="text-xs text-gray-500">库存: {{ item.stock }}</div>
              </div>
              <button 
                @click="exchangeItem(item)"
                :disabled="userPoints < item.points || item.stock === 0"
                :class="[
                  'exchange-btn',
                  userPoints >= item.points && item.stock > 0 ? 'available' : 'unavailable'
                ]"
              >
                {{ item.stock === 0 ? '已售罄' : userPoints >= item.points ? '立即兑换' : '积分不足' }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 兑换记录 -->
      <div class="exchange-history">
        <h3 class="text-lg font-bold text-gray-800 mb-4">
          <i class="fas fa-history text-blue-500 mr-2"></i>最近兑换
        </h3>
        <div class="space-y-3">
          <div 
            v-for="record in recentExchanges" 
            :key="record.id"
            class="history-item"
          >
            <div class="flex items-center">
              <img :src="record.image" :alt="record.name" class="history-image">
              <div>
                <div class="font-medium text-gray-800">{{ record.name }}</div>
                <div class="text-sm text-gray-500">{{ formatDate(record.exchangedAt) }}</div>
              </div>
            </div>
            <div class="text-right">
              <div class="font-medium text-blue-600">-{{ record.points }}积分</div>
              <div :class="['status-badge', getStatusClass(record.status)]">
                {{ getStatusText(record.status) }}
              </div>
            </div>
          </div>
        </div>
        <router-link 
          to="/client/exchange-history" 
          class="block text-center text-blue-600 hover:text-blue-700 mt-4 text-sm"
        >
          查看全部兑换记录
        </router-link>
      </div>
    </div>

    <!-- 兑换确认弹窗 -->
    <div v-if="showExchangeModal" class="modal-overlay">
      <div class="modal-content">
        <h3 class="modal-header">确认兑换</h3>
        <div class="modal-product">
          <img :src="selectedItem?.image" :alt="selectedItem?.name" class="modal-product-image">
          <div>
            <div class="font-medium text-gray-800">{{ selectedItem?.name }}</div>
            <div class="text-blue-600 font-bold">{{ selectedItem?.points }}积分</div>
          </div>
        </div>
        <div class="modal-summary">
          <div class="summary-row">
            <span class="text-gray-600">当前积分</span>
            <span class="font-medium">{{ userPoints }}</span>
          </div>
          <div class="summary-row">
            <span class="text-gray-600">兑换消耗</span>
            <span class="text-red-600 font-medium">-{{ selectedItem?.points }}</span>
          </div>
          <div class="summary-row">
            <span class="text-gray-800 font-medium">兑换后余额</span>
            <span class="font-bold text-blue-600">{{ userPoints - (selectedItem?.points || 0) }}</span>
          </div>
        </div>
        <div class="modal-actions">
          <button 
            @click="closeExchangeModal"
            class="modal-btn modal-btn-cancel"
          >
            取消
          </button>
          <button 
            @click="confirmExchange"
            class="modal-btn modal-btn-confirm"
          >
            确认兑换
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'

export default {
  name: 'PointsMall',
  setup() {
    const userPoints = ref(1250)
    const monthlyEarned = ref(320)
    const selectedCategory = ref('all')
    const sortBy = ref('default')
    const showExchangeModal = ref(false)
    const selectedItem = ref(null)
    
    // 分类
    const categories = ref([
      { key: 'all', name: '全部', icon: 'fas fa-th-large' },
      { key: 'electronics', name: '数码电子', icon: 'fas fa-mobile-alt' },
      { key: 'lifestyle', name: '生活用品', icon: 'fas fa-home' },
      { key: 'vouchers', name: '优惠券', icon: 'fas fa-ticket-alt' },
      { key: 'books', name: '图书文具', icon: 'fas fa-book' }
    ])
    
    // 热门商品
    const hotItems = ref([
      {
        id: 1,
        name: 'Apple AirPods Pro',
        description: '主动降噪无线耳机',
        points: 1800,
        originalPoints: 2000,
        discount: 9,
        image: '/api/placeholder/300/200',
        category: 'electronics',
        stock: 5,
        isHot: true
      },
      {
        id: 2,
        name: '星巴克咖啡券',
        description: '50元通用券，全国门店可用',
        points: 400,
        image: '/api/placeholder/300/200',
        category: 'vouchers',
        stock: 100,
        isHot: true
      },
      {
        id: 3,
        name: '小米移动电源',
        description: '10000mAh大容量快充',
        points: 600,
        image: '/api/placeholder/300/200',
        category: 'electronics',
        stock: 20,
        isHot: true
      }
    ])
    
    // 所有商品
    const allItems = ref([
      ...hotItems.value,
      {
        id: 4,
        name: 'Nintendo Switch',
        description: '任天堂游戏机',
        points: 2500,
        image: '/api/placeholder/300/200',
        category: 'electronics',
        stock: 2,
        isNew: true
      },
      {
        id: 5,
        name: '法律书籍套装',
        description: '专业法律参考书',
        points: 800,
        image: '/api/placeholder/300/200',
        category: 'books',
        stock: 15
      },
      {
        id: 6,
        name: '京东购物卡',
        description: '100元通用购物卡',
        points: 850,
        image: '/api/placeholder/300/200',
        category: 'vouchers',
        stock: 50
      }
    ])
    
    // 兑换记录
    const recentExchanges = ref([
      {
        id: 1,
        name: '星巴克咖啡券',
        points: 400,
        image: '/api/placeholder/100/100',
        exchangedAt: '2024-01-15 14:30:00',
        status: 'completed'
      },
      {
        id: 2,
        name: '小米移动电源',
        points: 600,
        image: '/api/placeholder/100/100',
        exchangedAt: '2024-01-10 10:15:00',
        status: 'shipping'
      }
    ])
    
    // 过滤和排序后的商品
    const filteredAndSortedItems = computed(() => {
      let filtered = allItems.value
      
      if (selectedCategory.value !== 'all') {
        filtered = filtered.filter(item => item.category === selectedCategory.value)
      }
      
      // 排序
      switch (sortBy.value) {
        case 'points-asc':
          filtered.sort((a, b) => a.points - b.points)
          break
        case 'points-desc':
          filtered.sort((a, b) => b.points - a.points)
          break
        case 'popularity':
          filtered.sort((a, b) => (b.isHot ? 1 : 0) - (a.isHot ? 1 : 0))
          break
        default:
          // 默认排序
          break
      }
      
      return filtered
    })
    
    // 获取分类名称
    const getCategoryName = (key) => {
      const category = categories.value.find(cat => cat.key === key)
      return category ? category.name : '全部商品'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      return dayjs(date).format('MM-DD HH:mm')
    }
    
    // 获取状态样式
    const getStatusClass = (status) => {
      const statusMap = {
        completed: 'bg-green-100 text-green-800',
        shipping: 'bg-blue-100 text-blue-800',
        pending: 'bg-yellow-100 text-yellow-800'
      }
      return statusMap[status] || 'bg-gray-100 text-gray-800'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        completed: '已完成',
        shipping: '配送中',
        pending: '处理中'
      }
      return statusMap[status] || '未知'
    }
    
    // 兑换商品
    const exchangeItem = (item) => {
      if (userPoints.value < item.points || item.stock === 0) return
      
      selectedItem.value = item
      showExchangeModal.value = true
    }
    
    // 关闭兑换弹窗
    const closeExchangeModal = () => {
      showExchangeModal.value = false
      selectedItem.value = null
    }
    
    // 确认兑换
    const confirmExchange = () => {
      if (!selectedItem.value) return
      
      // 扣除积分
      userPoints.value -= selectedItem.value.points
      
      // 减少库存
      selectedItem.value.stock -= 1
      
      // 添加到兑换记录
      recentExchanges.value.unshift({
        id: Date.now(),
        name: selectedItem.value.name,
        points: selectedItem.value.points,
        image: selectedItem.value.image,
        exchangedAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        status: 'pending'
      })
      
      // 关闭弹窗
      closeExchangeModal()
      
      // 显示成功提示
      alert(`兑换成功！您的${selectedItem.value.name}正在处理中`)
    }
    
    return {
      userPoints,
      monthlyEarned,
      selectedCategory,
      sortBy,
      categories,
      hotItems,
      filteredAndSortedItems,
      recentExchanges,
      showExchangeModal,
      selectedItem,
      getCategoryName,
      formatDate,
      getStatusClass,
      getStatusText,
      exchangeItem,
      closeExchangeModal,
      confirmExchange
    }
  }
}
</script>

<style scoped>
.points-mall {
  min-height: 100vh;
  background: #f8fafc;
}

.container {
  max-width: 1200px;
}

/* 顶部积分信息样式 */
.bg-gradient-to-r {
  background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
}

/* 分类标签样式 */
.category-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 24px;
}

.category-tab {
  padding: 8px 16px;
  border-radius: 9999px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  cursor: pointer;
  border: none;
  outline: none;
}

.category-tab.active {
  background: #3b82f6;
  color: white;
}

.category-tab:not(.active) {
  background: #f3f4f6;
  color: #374151;
}

.category-tab:not(.active):hover {
  background: #e5e7eb;
}

/* 商品卡片样式 */
.product-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #f1f5f9;
}

.product-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  background: #f8fafc;
}

.product-info {
  padding: 16px;
}

.product-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
  line-height: 1.4;
}

.product-description {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 12px;
  line-height: 1.5;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.points-text {
  font-size: 18px;
  font-weight: 700;
  color: #3b82f6;
}

.points-unit {
  font-size: 12px;
  color: #6b7280;
  margin-left: 4px;
}

.original-points {
  font-size: 12px;
  color: #9ca3af;
  text-decoration: line-through;
  margin-left: 8px;
}

.exchange-btn {
  width: 100%;
  padding: 10px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.exchange-btn.available {
  background: #3b82f6;
  color: white;
}

.exchange-btn.available:hover {
  background: #2563eb;
}

.exchange-btn.unavailable {
  background: #d1d5db;
  color: #6b7280;
  cursor: not-allowed;
}

/* 标签样式 */
.badge {
  position: absolute;
  top: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.badge-hot {
  left: 8px;
  background: #ef4444;
}

.badge-new {
  right: 8px;
  background: #10b981;
}

.badge-low-stock {
  left: 8px;
  background: #f59e0b;
}

.badge-discount {
  right: 8px;
  background: #f59e0b;
}

/* 兑换记录样式 */
.exchange-history {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 24px;
  margin-top: 32px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f1f5f9;
}

.history-item:last-child {
  border-bottom: none;
}

.history-image {
  width: 48px;
  height: 48px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 12px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 16px;
}

.modal-content {
  background: white;
  border-radius: 12px;
  max-width: 400px;
  width: 100%;
  padding: 24px;
  box-shadow: 0 20px 64px rgba(0, 0, 0, 0.2);
}

.modal-header {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 16px;
}

.modal-product {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.modal-product-image {
  width: 64px;
  height: 64px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 16px;
}

.modal-summary {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.summary-row:last-child {
  margin-bottom: 0;
  padding-top: 8px;
  border-top: 1px solid #e2e8f0;
}

.modal-actions {
  display: flex;
  gap: 12px;
}

.modal-btn {
  flex: 1;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.modal-btn-cancel {
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
}

.modal-btn-cancel:hover {
  background: #f9fafb;
}

.modal-btn-confirm {
  background: #3b82f6;
  color: white;
}

.modal-btn-confirm:hover {
  background: #2563eb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .points-mall {
    padding: 0;
  }
  
  .container {
    padding-left: 16px;
    padding-right: 16px;
  }
  
  header .container {
    padding: 16px;
  }
  
  .product-image {
    height: 160px;
  }
  
  .product-info {
    padding: 12px;
  }
  
  .product-title {
    font-size: 14px;
  }
  
  .product-description {
    font-size: 12px;
  }
  
  .points-text {
    font-size: 16px;
  }
  
  .exchange-btn {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  .exchange-history {
    padding: 16px;
    margin-top: 24px;
  }
  
  .modal-content {
    padding: 20px;
    margin: 16px;
  }
  
  .modal-product-image {
    width: 48px;
    height: 48px;
  }
}

@media (max-width: 480px) {
  .category-tabs {
    gap: 6px;
    margin-bottom: 16px;
  }
  
  .category-tab {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .grid {
    grid-template-columns: repeat(2, 1fr) !important;
    gap: 12px;
  }
  
  .product-title {
    font-size: 13px;
    margin-bottom: 6px;
  }
  
  .product-description {
    font-size: 11px;
    margin-bottom: 8px;
  }
  
  .points-text {
    font-size: 14px;
  }
  
  .exchange-btn {
    padding: 6px 8px;
    font-size: 11px;
  }
}

/* 工具类样式 */
.text-gradient {
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.hover-scale {
  transition: transform 0.3s ease;
}

.hover-scale:hover {
  transform: scale(1.02);
}

.loading-skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}
</style> 